package 回溯;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author tmh
 * @date 2024/9/8 16:11
 * @description
 */
public class T17电话号码的字母组合 {
    String[] mapping = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    StringBuilder builder = new StringBuilder("");
    List<String> result = new ArrayList<>();

    public List<String> letterCombinations(String digits) {
        if (digits==null||digits.length()==0){
            return Collections.emptyList();
        }
        backTracking(digits,0);
        return result;
    }

    /**
     * @param str    "23"
     * @param num    表示处理哪个数字对应的映射，例如 num:0,对应2 ,处理2对应的映射
     */
    public void backTracking(String str, int num) {
        if (str.length() == num) {
            result.add(builder.toString());
            return;
        }
        //获得当前字符串
        String letter=mapping[str.charAt(num)-'0'];
        //遍历当前字符串
        for (char c : letter.toCharArray()) {
            builder.append(c);
            //递归处理下一个字符串
            backTracking(str,num+1);
            //回溯-移除builder里面的最后一个字符
            builder.deleteCharAt(builder.length()-1);
        }
    }
}
